package com.qd.p2p.web.action.user;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

import com.opensymphony.xwork2.ModelDriven;
import com.qd.p2p.adapter.AdaptedRequestHandleService;
import com.qd.p2p.adapter.PlatformInfo;
import com.qd.p2p.web.action.borrow.BorrowAction;
import com.qdlc.p2p.biz.service.MemberInfosService;
import com.qdlc.p2p.biz.service.UserCacheService;
import com.qdlc.p2p.biz.service.UserIdentifyService;
import com.qdlc.p2p.biz.service.UserPwdQuestionService;
import com.qdlc.p2p.biz.service.UserService;
import com.qdlc.p2p.biz.tpp.TppBaseInterface;
import com.qdlc.p2p.biz.tpp.TppServiceFactory;
import com.qdlc.p2p.biz.web.action.BaseAction;
import com.qdlc.p2p.common.constant.Constant;
import com.qdlc.p2p.dal.checkrule.RealNameAttestationRuleCheck;
import com.qdlc.p2p.dal.common.RuleCheckHelper;
import com.qdlc.p2p.dal.dto.MemberInfos;
import com.qdlc.p2p.dal.dto.User;
import com.qdlc.p2p.dal.dto.UserIdentify;
import com.qdlc.p2p.dal.dto.UserPwdQuestion;
import com.qdlc.p2p.dal.model.TppModel;
import com.qdlc.p2p.dal.model.UserModel;
import com.qdlc.p2p.dal.util.UserTypeUtils;
import com.qdlc.p2p.dal.util.UserUtils;

/**
 * 安全中心
 *
 * @author sj
 * @version 2.0
 * @since 2014年2月25日16:57:51
 */

public class SecurityAction extends BaseAction<UserModel> implements ModelDriven<UserModel> {

	private Logger logger = Logger.getLogger(BorrowAction.class);
	private Map<String, Object> data;

	@Resource
	private UserService userService;
	@Resource
	private UserIdentifyService userIdentifyService;
	@Resource
	private UserCacheService userCacheService;
	@Resource
	private UserPwdQuestionService userPwdQuestionService;

	@Resource
	MemberInfosService memberInfosService;

	@Resource
	private AdaptedRequestHandleService adaptedRequestHandleService;

	private User user;

	private RealNameAttestationRuleCheck realNameAttestationRuleCheck = RuleCheckHelper
			.getValue(RealNameAttestationRuleCheck.class);

	/**
	 * 前往安全中心设置页面
	 *
	 * @return
	 * @throws Exception
	 */
	@Action(value = "/member/security/setting", results = {
			@Result(name = "setting", type = "ftl", location = "/member/security/setting.html"),
			@Result(name = "borrow_setting", type = "ftl", location = "/member_borrow/security/setting.html") })
	public String setting() throws Exception {

		// 清判断跳转页面用Flag
		request.getSession().removeAttribute("returnFlag");

		request.setAttribute("real_name_style", realNameAttestationRuleCheck.style());

		// 更新下userIdentify缓存
		// UserIdentify userIdentify = UserLoginUtil.getUserIdentify();
		// TODO:UserIdentify
		// session.put(Constant.SESSION_USER_IDENTIFY, userIdentifyService.findById(userIdentify.getId()));

		// 获取Session中的用户对象
		user = getSessionUser();
		UserIdentify userIdentify = userIdentifyService.findByUserId(user.getUserId());
		// 判断交易密码是否已设置
		request.setAttribute("payPwd", user.getPayPwd());

		// 密保问题List取得
		List<UserPwdQuestion> list = userPwdQuestionService.pwdQuestion(user);
		// 密保已设置的场合、设置/修改按钮显示判断用Flag设定值
		if ((list != null) && (list.size() > 0)) {
			request.setAttribute("pwdQuestion", 1);
		}
		request.setAttribute("emailStatus", userIdentify.getEmailStatus());
		request.setAttribute("realNameStatus", userIdentify.getRealNameStatus());
		request.setAttribute("session_user_identify", userIdentify);
		UserModel model = UserModel.instance(user);
		double securityValue = model.initSecurityValue(userIdentify);
		request.setAttribute("securityValue", securityValue);

		if (UserTypeUtils.isBorrowOrInverstment(user.getUserId())) {
			MemberInfos memberInfos = memberInfosService.findByUserId(user.getUserId());
			request.setAttribute("memberInfos", memberInfos);
			request.setAttribute("user", user);
			return "borrow_setting";
		}
		return "setting";
	}

	/**
	 * 实名认证
	 *
	 * @return String
	 * @throws Exception if has error
	 */
	@Action(value = "/member/security/realname", results = {
			@Result(name = "pnrregister", type = "ftl", location = "/tpp/chinapnr/userRegister.html") })
	public String realname() throws Exception {
		user = getSessionUser();
		Object obj = userCacheService.doRealname(user, model);
		if (obj != null) {
			return madeApiRegisterReturn(obj, user);
		}
		UserIdentify userIdentify = userIdentifyService.findByUserId(user.getUserId());
		// 更新session中real_name_status的状态
		userIdentify.setRealNameStatus(2);
		// TODO:UserIdentify
		// session.put(Constant.SESSION_USER_IDENTIFY, userIdentify);
		data = new HashMap<String, Object>();
		data.put("result", true);
		printWebJson(getStringOfJpaObj(data));
		return null;
	}

	/**
	 * 第三方授权
	 *
	 * @return
	 * @throws IOException
	 */
	@Action(value = "/member/tpp/loanAuthorize", results = {
			@Result(name = "result", type = "ftl", location = "/member/tpp/" + Constant.TPP_PACKAGE
					+ "/loanAuthorize.html"),
			@Result(name = "isAuthorize", type = "ftl", location = "/member/tpp/" + Constant.TPP_PACKAGE
					+ "/isAuthorize.html") })
	public String tppLoanAuthorize() throws IOException {
		User sessionUser = getSessionUser();
		UserIdentify userIdentify = userIdentifyService.findByUserId(sessionUser.getUserId());
		model.validTppLoanAuthorize(userIdentify);
		if (userIdentify.isAuthorize()) {
			request.setAttribute("sessionUser", sessionUser);
			request.setAttribute("loanAuthorizeType", userIdentify.getAuthorizeType());
			return "isAuthorize";
		}
		PlatformInfo platformInfo = adaptedRequestHandleService.getPlatformInfo();
		request.setAttribute("domain", platformInfo.getDomain());
		request.setAttribute("merchantId", platformInfo.getMerchantId());
		request.setAttribute("terminalId", platformInfo.getTerminalId());
		request.setAttribute("tppUserCustId", sessionUser.getTppUserCustId());
		return "result";
	}

	@Action(value = "/tpp/tppAction/authCallBack")
	public void tppAuthCallBack() throws Exception {
		PlatformInfo platformInfo = adaptedRequestHandleService.getPlatformInfo();
		String result = paramString("result");
		String sign = paramString("sign");

		String tppId = null;
		String code = null;
		String successCode = "success";
		if ("baofoo".equalsIgnoreCase(platformInfo.getName())) {
			// TODO 存在判读的隐患
			successCode = "CSD000";
			if (StringUtils.isNotBlank(result) && StringUtils.isNotBlank(sign)
					&& sign.equals(adaptedRequestHandleService.signMd5(result))) {
				InputStream is = new ByteArrayInputStream(result.getBytes());
				SAXReader sax = new SAXReader();
				try {
					Document xmlDoc = sax.read(is);
					Element root = xmlDoc.getRootElement();
					Node userIdNode = root.selectSingleNode("//user_id");
					Node codeNode = root.selectSingleNode("//code");
					tppId = userIdNode.getText();
					code = codeNode.getText();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		if ((code != null)) {
			if ((tppId != null) && code.equals(successCode)) {
				User u = userService.findByTppId(tppId);
				if (u != null) {
					userIdentifyService.modifyTppAuthorizeStatus(u.getUserId(), true, platformInfo.getName());
					UserIdentify userIdentify = userIdentifyService.findByUserId(u.getUserId());
					session.put(Constant.SESSION_USER_IDENTIFY, userIdentify);
					printWebSuccess();
				}
			}
		}
		printWebResult("授权失败", false);
	}

	/**
	 * 处理不同第三方接口
	 *
	 * @param object
	 * @param user 用户
	 * @return 返回的页面
	 */
	private String madeApiRegisterReturn(Object object, User user) {
		message("实名认证申请成功，请到个人中心查看", "/member/main.html");
		return MSG;
	}

	/**
	 * 密保问题展示页面
	 *
	 * @return
	 * @throws Exception
	 */
	@Action("/member/security/pwdQuestion")
	public String pwdQuestion() throws Exception {
		user = getSessionUser();
		List<UserPwdQuestion> list = userPwdQuestionService.pwdQuestion(user);
		if ((list != null) && (list.size() > 0)) {
			request.setAttribute("list", list);
			return "pwdQuestion";
		} else {
			// 判断跳转页面用Flag(null：跳转到设置密保页面;1：跳转到安全中心页面)
			request.getSession().setAttribute("returnFlag", 1);
			// 判断按钮名称显示用Flag(1：确认；1以外：确认修改;)
			// 未设置密保的场合、按钮名称：确认
			request.setAttribute("showFlag", 1);
			return "setPwdQuestion";
		}
	}

	/**
	 * 回答密保问题页面
	 *
	 * @return
	 * @throws Exception
	 */
	@Action("/member/security/answerPwdQuestion")
	public String answerPwdQuestion() throws Exception {
		user = getSessionUser();
		List<UserPwdQuestion> list = userPwdQuestionService.pwdQuestion(user);
		request.setAttribute("list", list);
		return "answerPwdQuestion";
	}

	/**
	 * 回答密保问题
	 *
	 * @return
	 * @throws Exception
	 */
	@Action("/member/security/doAnswerPwdQuestion")
	public void doAnswerPwdQuestion() throws Exception {
		user = getSessionUser();
		userPwdQuestionService.doAnswerPwdQuestion(model, user);
		printWebSuccess();
	}

	/**
	 * 设置密保问题页面
	 *
	 * @return
	 * @throws Exception
	 */
	@Action("/member/security/setPwdQuestion")
	public String setPwdQuestion() throws Exception {

		// 判断跳转页面用Flag(null：跳转到设置密保页面;1：跳转到安全中心页面)
		if (request.getSession().getAttribute("returnFlag") == null) {
			request.getSession().setAttribute("returnFlag", 1);
		}
		return "setPwdQuestion";
	}

	/**
	 * 设置密保问题
	 *
	 * @return
	 * @throws Exception
	 */
	@Action("/member/security/doSetPwdQuestion")
	public void doSetPwdQuestion() throws Exception {
		user = getSessionUser();
		userPwdQuestionService.doSetPwdQuestion(model, user);
		printWebSuccess();
	}

	/**
	 * 第三方账户开户
	 *
	 * @return
	 */

	/*
	 * @Action(value="/member/security/tppRegisger",results = {
	 * 
	 * @Result(name = "result", type = "ftl", location = "/member/tpp/"+Constant.TPP_PACKAGE+"/register.html")
	 * })
	 */
	@Action(value = "/member/security/tppRegisger")
	public String tppRegisger() {
		User user = this.getSessionUser();
		Object obj = userCacheService.tppRealName(model, user);
		request.setAttribute("reg", obj);
		return "result";
	}

	/**
	 * 第三方账户登录
	 *
	 * @return
	 */
	@Action(value = "/member/tpp/apiLogin", results = {
			@Result(name = "result", type = "ftl", location = "/member/tpp/" + Constant.TPP_PACKAGE + "/login.html") })
	public String tppLogin() {
		User user = this.getSessionUser();
		user = userService.getUserById(user.getUserId());
		String tppUserCustId = UserUtils.getUserTppCustId(user.getUserId());
		if (StringUtils.isBlank(tppUserCustId)) {
			message("请先开通过第三方托管账户！", "/member/security/setting.html", "前往开通》》》》");
			return MSG;
		}
		TppModel tppModel = new TppModel();
		tppModel.setUser(user);
		TppBaseInterface tppService = TppServiceFactory.newIntance();
		Object loginObj = tppService.tppUserLogin(tppModel);
		request.setAttribute("login", loginObj);
		return "result";
	}
}
